package com.crawler.harbour.task;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.crawler.harbour.common.DockCode;
import com.crawler.harbour.entity.XmyhShipMent;
import com.crawler.harbour.model.Notice;
import com.crawler.harbour.model.ShipmentNew;
import com.crawler.harbour.service.INoticeService;
import com.crawler.harbour.service.IShipmentNewService;
import com.crawler.harbour.utils.RuoKuai;
import com.crawler.harbour.utils.StorageDay;
import com.crawler.harbour.utils.UrlUtil;
import com.crawler.utils.BeanUtils;
import com.crawler.utils.RedisManager;
import com.crawler.harbour.utils.StringUtils;

import net.dongliu.requests.Requests;
import net.dongliu.requests.Response;
import net.dongliu.requests.Session;

/**
 * 厦门远海码头船期查询
 *
 * @author wbsheng
 * @create 2018-04-12 15:04
 **/
@Service
@Lazy(false)
public class XMYHTask extends StorageDay{

    private static final Logger LOGGER = LoggerFactory.getLogger(XMYHTask.class);

    @Autowired
    IShipmentNewService shipmentNewService;

    @Autowired
    private INoticeService noticeService;

    /**
     * 远海码头查询
     *
     * @throws IOException
     */
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void searchShipMent() throws IOException {
    	if(!RedisManager.lock("ship:searchShipMent", 0)) {
    		return;
    	}
        Session session = Requests.session();
        List<XmyhShipMent> resultList = new ArrayList<>();
        List<ShipmentNew> shipmentNewList = new ArrayList<>();
        //获取数据
        Response<String> textResponse = session.get(UrlUtil.XMYHSHIPMENTONE).send().toTextResponse();
        Document document = Jsoup.parse(textResponse.getBody());
        //数据转化javabean封装到resultList
        handleData(resultList, document);
        Element reportBeanDiv = document.getElementById("queryShipReportBeanDiv");
        //页数字符串
        String totalStr = reportBeanDiv.text().replaceAll(" ", "");
        Integer totalPage = Integer.parseInt(totalStr.substring(totalStr.lastIndexOf("条记录") + 3, totalStr.lastIndexOf("当前第") - 1));
        LOGGER.info("离港总页数" + totalPage);
        LOGGER.info("离港第1页抓去数据：" + resultList.size());
        int whileCount = 2;
        //循环获取，不用修改当前第几页 系统会根据请求次数依次增加
        while (whileCount <= totalPage) {
            textResponse = session.get(UrlUtil.XMYHSHIPMENTWEILIGANGMORE).send().toTextResponse();
            document = Jsoup.parse(textResponse.getBody());
            handleData(resultList, document);
            LOGGER.info("离港第" + whileCount + "页抓去数据：" + resultList.size());
            whileCount++;
        }
        textResponse = session.get(UrlUtil.XMYHSHIPMENTLIGANG).send().toTextResponse();
        document = Jsoup.parse(textResponse.getBody());
        handleData(resultList, document);
        reportBeanDiv = document.getElementById("queryShipReportBeanDiv");
        totalStr = reportBeanDiv.text().replaceAll(" ", "");
        totalPage = Integer.parseInt(totalStr.substring(totalStr.lastIndexOf("条记录") + 3, totalStr.lastIndexOf("当前第") - 1));
        LOGGER.info("未离港总页数" + totalPage);
        LOGGER.info("未离港第1页抓去数据：" + resultList.size());
        whileCount = 2;
         //循环获取，不用修改当前第几页 系统会根据请求次数依次增加
        while (whileCount <= totalPage) {
            textResponse = session.get(UrlUtil.XMYHSHIPMENTLIGANGMORE).send().toTextResponse();
            document = Jsoup.parse(textResponse.getBody());
            handleData(resultList, document);
            LOGGER.info("未离港第" + whileCount + "页抓去数据：" + resultList.size());
            whileCount++;
        }
        Date date = new Date();
        List<String> IdList =new ArrayList<>();
        if (resultList != null && resultList.size() > 0) {
            for (XmyhShipMent shipMent: resultList ) {
            	ShipmentNew shipmentNew = new ShipmentNew(); 
            	String hashStr = null;
            	if(shipMent.getLeavePort().equals("否")) {
            		hashStr = RuoKuai.MD5(DockCode._YHT+shipMent.getShipEnName() + shipMent.getImportVoyage()+shipMent.getExportVoyage()+"_1");
            	}else {
            		hashStr = RuoKuai.MD5(DockCode._YHT+shipMent.getShipEnName() + shipMent.getImportVoyage()+shipMent.getExportVoyage()+"_1");
            	}
                shipMent.setId(hashStr);
                shipmentNew.setId(hashStr);
                ShipmentNew temp1 = shipmentNewService.selectById(hashStr);
                Notice notice = new Notice();
                notice.setPortNo(DockCode._YHT);
                shipmentNew.setWharfName("远海码头");
                notice.setShipName(shipMent.getShipEnName());
                notice.setShipCnName(shipMent.getShipCnName());
                notice.setJkShipTimer(shipMent.getImportVoyage());
                notice.setCkShipTimer(shipMent.getExportVoyage());
                notice.setJkSailingDate(shipMent.getPlanBerthing());
                notice.setCkSailingDate(shipMent.getPlanToBerth());
                notice.setIntoDate(convertTime(shipMent.getPortOpeningTime()));
                notice.setOffDate(convertTime(shipMent.getCutOffBox()));
                notice.setBerthDate(shipMent.getPlanBerthing());
                notice.setLeaveDate(shipMent.getPlanToBerth());
                notice.setCutOffDate(convertTime(shipMent.getCustomsClearance()));
                notice.setStatus(0);
                if(StringUtils.isBlank(notice.getShipName())) {
                	notice.setShipName(notice.getShipCnName());
                }
                notice.setCreateTime(date);
                
                shipmentNew.setSvcName(shipMent.getRoute());
                shipmentNew.setShipTimer(shipMent.getImportVoyage());
                shipmentNew.setAgent(shipMent.getShippingAgency());
                shipmentNew.setXzCutDate(convertTime(shipMent.getFumigatingBox()));
                shipmentNew.setOffLadingDate(shipMent.getWharfIntercepting());
                shipmentNew.setStatus(shipMent.getLeavePort());
                BeanUtils.copyProperties(notice,shipmentNew , "id","status","type","shipTimer","sailingDate");
                shipmentNew.setType(1);
                shipmentNew.setSailingDate(notice.getJkSailingDate());
                shipmentNewList.add(shipmentNew);
                ShipmentNew shipmentNew2 =new ShipmentNew();
                BeanUtils.copyProperties(shipmentNew,shipmentNew2);
                if(shipMent.getLeavePort().equals("否")) {
                	hashStr = RuoKuai.MD5(DockCode._YHT+shipMent.getShipEnName() +shipMent.getImportVoyage()+ shipMent.getExportVoyage()+"未离港"+"_2");
            	}else {
            		hashStr = RuoKuai.MD5(DockCode._YHT+shipMent.getShipEnName() +shipMent.getImportVoyage()+ shipMent.getExportVoyage()+"离港"+"_2");
            	}
                ShipmentNew temp2 = shipmentNewService.selectById(hashStr);
                shipmentNew2.setId(hashStr);
                shipmentNew2.setShipTimer(shipMent.getExportVoyage());
                shipmentNew2.setType(2);
                shipmentNew2.setSailingDate(notice.getCkSailingDate());
                shipmentNewList.add(shipmentNew2);
                boolean isOk = true;
    	        if(temp1!=null&&IdList.contains(temp1.getId())||temp2!=null&&IdList.contains(temp2.getId())) {
    	        	isOk = false;
    	        }
    		    if(isOk) {
	                    if(temp1 != null &&!temp1.getSailingDate().equals(shipmentNew.getSailingDate())){
	                    	if(StringUtils.nuller(temp1.getSailingDate()).equals("")) {
	                    		notice.setType(0);
	                    	}else {
	                    		notice.setType(4);
	                    	}
	                        notice.setId(null);
	                        notice.setOrigValue(temp1.getSailingDate());
	                        noticeService.insert(notice);
	                    }
	                    if(temp2 != null &&!temp2.getSailingDate().equals(shipmentNew2.getSailingDate())){
	                    	if(StringUtils.nuller(temp2.getSailingDate()).equals("")) {
	                    		notice.setType(0);
	                    	}else {
	                    		notice.setType(1);
	                    	}
	                        notice.setId(null);
	                        notice.setOrigValue(temp2.getSailingDate());
	                        noticeService.insert(notice);
	                    }
	                    if(temp2 != null &&!temp2.getOffDate().equals(convertTime(shipMent.getCutOffBox()))){
	                        notice.setType(2);
	                        notice.setId(null);
	                        notice.setOrigValue(temp2.getOffDate());
	                        noticeService.insert(notice);
	                    }
	                    if(temp2 != null &&!temp2.getIntoDate().equals(convertTime(shipMent.getPortOpeningTime()))){
	                        notice.setType(3);
	                        notice.setId(null);
	                        notice.setOrigValue(temp2.getIntoDate());
	                        noticeService.insert(notice);
	                    }
	                    if(temp1!=null) {
                        	IdList.add(temp1.getId());
                        }
	                    if(temp2!=null) {
                        	IdList.add(temp2.getId());
                        }
    		    }
           }
            shipmentNewService.insertOrUpdateAllColumnBatch(shipmentNewList, resultList.size());
        }
            
    }

    /**
     * 处理数据
     *
     * @param resultList
     * @param document
     */
    private void handleData(List<XmyhShipMent> resultList, Document document) {
        Element table = document.getElementById("queryShipReportBeanDiv");
        Elements trs = table.getElementsByTag("tr");
        int mark = 0;
        for (Element tr : trs) {
            if (mark <= 4) {
                mark++;
                continue;
            }
            Elements tds = tr.getElementsByTag("td");
            XmyhShipMent shipMent = new XmyhShipMent(
                    tds.get(8).text(),
                    tds.get(13).text(),
                    tds.get(6).text(),
                    tds.get(10).text(),
                    tds.get(1).text(),
                    tds.get(2).text(),
                    tds.get(7).text(),
                    tds.get(4).text(),
                    tds.get(12).text(),
                    tds.get(3).text(),
                    tds.get(11).text(),
                    tds.get(5).text(),
                    tds.get(14).text(),
                    tds.get(0).text(),
                    tds.get(9).text()
            );
            resultList.add(shipMent);
        }
    }
    private static String convertTime(String date) {
    	if(StringUtils.isBlank(date)) {
    		return "";
    	}    	
    	return date.substring(0, date.indexOf("星"));    	
    }
}
